package com.hunan.chinamobile.manager;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hunan.chinamobile.constant.SysConstant;
import com.hunan.chinamobile.core.Result;
import com.hunan.chinamobile.core.ResultGenerator;
import com.hunan.chinamobile.dto.PasswordDTO;
import com.hunan.chinamobile.dto.UserDTO;
import com.hunan.chinamobile.model.City;
import com.hunan.chinamobile.model.Role;
import com.hunan.chinamobile.model.User;
import com.hunan.chinamobile.security.TokenAuthenticationService;
import com.hunan.chinamobile.service.CityService;
import com.hunan.chinamobile.service.HUserService;
import com.hunan.chinamobile.service.RoleService;
import com.hunan.chinamobile.util.MD5Utils;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private HUserService hUserService;
    @Resource
    private CityService cityService;
    @Resource
    private RoleService roleService;

    @PostMapping
    public Result add(@RequestBody User user){
        if(user == null || StringUtils.isEmpty(user.getUserName()) || StringUtils.isEmpty(user.getPassword())){
            return ResultGenerator.genFailResult("参数为空");
        }
        if(hUserService.check(user.getUserName()) != null){
            return ResultGenerator.genFailResult("该用户名已存在");
        }

        if(StringUtils.isEmpty(user.getRoleId())) {
            Role role;
            if (StringUtils.isEmpty(user.getCityId())) {
                role = roleService.findRoleByName(SysConstant.ROLE_OPERATION);
            }else{
                role = roleService.findRoleByName(SysConstant.ROLE_USER);
            }
            if(role != null){
                user.setRoleId(role.getId());
            }
        }
        user.setId(UUID.randomUUID().toString());
        user.setPassword(MD5Utils.encryptMD5Data(user.getPassword()));
        user.setCreatedAt(new Date());
        user.setUpdatedAt(new Date());
        hUserService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    @PutMapping
    public Result update(@RequestBody User user){
        if(user == null || StringUtils.isEmpty(user.getUserName())){
            return ResultGenerator.genFailResult("参数为空");
        }
        user.setUpdatedAt(new Date());
        hUserService.update(user);
        return ResultGenerator.genSuccessResult();
    }


    @DeleteMapping("/{id}")
    public Result del(@PathVariable String id){
        hUserService.deleteById(id);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping
    public Result list(@RequestParam(required = false) String name,
                       @RequestParam(required = false) String roleId,
                       @RequestParam(name = "page", defaultValue = "1") Integer page,
                       @RequestParam(name = "size", defaultValue = "20") Integer size){
        if(StringUtils.isEmpty(roleId)){
            return ResultGenerator.genFailResult("参数roleId为空！");
        }
        PageHelper.startPage(page,size);
        List<User> users = hUserService.findByRoleAndUserName(roleId,name);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    @PostMapping("/updatePwd")
    public Result updatePassword(@RequestBody PasswordDTO passwordDTO){
        if(StringUtils.isEmpty(passwordDTO.getUserId()) || StringUtils.isEmpty(passwordDTO.getOldPwd())
                || StringUtils.isEmpty(passwordDTO.getNewPwd())){
            return ResultGenerator.genFailResult("参数为空！");
        }
        User u = hUserService.findById(passwordDTO.getUserId());
        if(u == null) return ResultGenerator.genFailResult("该用户不存在");

        if(MD5Utils.encryptMD5Data(passwordDTO.getOldPwd()).equals(u.getPassword())){
            u.setPassword(MD5Utils.encryptMD5Data(passwordDTO.getNewPwd()));
            u.setUpdatedAt(new Date());
            hUserService.update(u);
            return ResultGenerator.genSuccessResult();
        }else{
            return ResultGenerator.genFailResult("原密码错误！");
        }
    }

    @GetMapping("/me")
    public Result getLoginInfo(HttpServletRequest request, HttpServletResponse response){
        Authentication authentication = TokenAuthenticationService.getAuthentication(request, response);
        if (authentication == null) {
            return null;
        }
        UserDTO userDTO = hUserService.findByUserName(authentication.getPrincipal().toString());
        userDTO.setPassword(null);
        if(!StringUtils.isEmpty(userDTO.getCityId())){
            City city = cityService.findById(userDTO.getCityId());
            if(city != null){
                userDTO.setCityName(city.getCityName());
            }
        }
        return ResultGenerator.genSuccessResult(userDTO);
    }
}
